package com.goresor.service;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.api.client.googleapis.json.JsonCContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.goresor.controller.OAuth10aController;
import com.goresor.model.Loc;
import com.goresor.model.LocList;
import com.goresor.util.GoogleTransportUtil;
import com.goresor.util.GoogleUrlFactory;

@Component
@SuppressWarnings("deprecation")
public class LocationProviderImpl implements ILocationProvider {

	public static final Logger log = LoggerFactory
	.getLogger(LocationProviderImpl.class);
	
	@Autowired
	private GoogleUrlFactory urlFactory = new GoogleUrlFactory() ;

	public List<Loc> getLocationsList() throws IOException {
		HttpRequest request = GoogleTransportUtil.TRANSPORT.buildGetRequest();
		request.url = urlFactory.getLatitudeUrlForLocations();
		return request.execute().parseAs(LocList.class).items;
	}

	public Loc getLocation(Long timestampMs) throws IOException {
		HttpRequest request = GoogleTransportUtil.TRANSPORT.buildGetRequest();
		request.url = urlFactory.getLatitudeUrlForLocation(timestampMs);
		return request.execute().parseAs(Loc.class);
	}

	public Loc getLocationCurrent() throws IOException {
		HttpRequest request = GoogleTransportUtil.TRANSPORT.buildGetRequest();
		request.url = urlFactory.getLatitudeUrlForCurrentLocation();
		log.info("url current location " + request.url);
		HttpResponse execute = request.execute();
		return execute.parseAs(Loc.class);
	}

	public Loc updateCurrent() throws IOException {
		HttpRequest request = GoogleTransportUtil.TRANSPORT.buildPutRequest();
		request.content = toContent();
		request.url = urlFactory.getLatitudeUrlForCurrentLocation();
		return request.execute().parseAs(Loc.class);
	}

	public void executeDelete(Long timestampMs) throws IOException {
		HttpRequest request = GoogleTransportUtil.TRANSPORT.buildDeleteRequest();
		request.url = urlFactory.getLatitudeUrlForLocation(timestampMs);
		request.execute().ignore();
	}

	public void executeDeleteCurrent() throws IOException {
		HttpRequest request = GoogleTransportUtil.TRANSPORT.buildDeleteRequest();
		request.url = urlFactory.getLatitudeUrlForCurrentLocation();
		request.execute().ignore();
	}

	private JsonCContent toContent() {
		JsonCContent content = new JsonCContent();
		content.jsonFactory = GoogleTransportUtil.JSON_FACTORY;
		content.data = this;
		return content;
	}
}
